const STATUS = {
    PENDING: "pending",
    FULFILLED: "fulfilled",
    REJECTED: "rejected"
}


class MyPromise {
    constructor(executor) {
        this.status = STATUS.PENDING
        this.value = undefined
        this.reason = undefined

        this.onFulfilledCallbacks = []
        this.onRejectedCallbacks = []

        const resolve = (value) => {
            if (this.status === STATUS.PENDING) {
                this.status = STATUS.FULFILLED
                this.value = value

                // 发布过程
                this.onFulfilledCallbacks.forEach(fn => fn())
            }

        }

        const reject = (reason) => {
            if (this.status === STATUS.PENDING) {
                this.status = STATUS.REJECTED
                this.reason = reason
            }

            this.onRejectedCallbacks.forEach(fn => fn())
        }

        try {
            executor(resolve, reject);
        } catch (e) {
            reject(e)
        }

    }

    then(onFulfilled, onRejected) {
        if (this.status === STATUS.FULFILLED) {
            onFulfilled(this.value)
        }

        if (this.status === STATUS.REJECTED) {
            onRejected(this.reason)
        }

        // 异步处理
        if(this.status === STATUS.PENDING) {
            // 订阅过程(发布订阅模式)
            this.onFulfilledCallbacks.push(() => {
                onFulfilled(this.value)
            })

            this.onRejectedCallbacks.push(() =>{
                onRejected(this.reason)
            })
        }

        return this
    }
}

module.exports = MyPromise;